import datetime
import math
import time
import threading
import random
from flask import Blueprint, render_template, jsonify,request
from sqlalchemy import null,desc
from applications.extensions import db
from applications.common import curd
from applications.common.utils.rights import authorize
from applications.models import TrainData2, TrainData, SignsData2

admin_scene_realtime = Blueprint('adminSceneRealTime', __name__, url_prefix='/admin/scene_realtime')

train = null
# 实时训练
@admin_scene_realtime.get('/')
def main():

    police_name = '张三'
    scene_type = '攻防急症'
    train_type = '打斗攻防情景训练'
    Blood_oxygen = round(random.uniform(96, 98),2)
    blood_pressure = random.randint(110, 115)
    Respiratory_rate = random.randint(18, 26)
    heart_rate = random.randint(65, 80)
    temperature = round(random.uniform(36.2, 36.7),2)
    # 当前时间
    time_now = time.strftime('%H:%M:%S ', time.localtime(time.time()))
    return render_template('admin/atkdef_scene/scene_realtime2.html',
                           Blood_oxygen=Blood_oxygen,
                           blood_pressure=blood_pressure,
                           Respiratory_rate=Respiratory_rate,
                           heart_rate=heart_rate,
                           temperature=temperature,
                           start_time=time_now,
                           user_name=police_name,
                           scene_name=scene_type,
                           train_name=train_type,
                           )


#  实时训练（2）
@admin_scene_realtime.get('/details/<int:id>')
def edit(id):
    global train
    train = curd.get_one_by_id(TrainData2, id)
    Blood_oxygen = round(random.uniform(96, 98), 2)
    blood_pressure = random.randint(110, 115)
    Respiratory_rate = random.randint(18, 26)
    heart_rate = random.randint(65, 80)
    temperature = round(random.uniform(36.2, 36.7), 2)
    return render_template('admin/atkdef_scene/scene_realtime2.html',
                           Blood_oxygen=Blood_oxygen,
                           blood_pressure=blood_pressure,
                           Respiratory_rate=Respiratory_rate,
                           heart_rate=heart_rate,
                           temperature=temperature,
                           user_name=train.user_name,
                           scene_name=train.scene_name,
                           train_name=train.train_name,
                           start_time=train.start_time,
                           trainId=id
                           )


# 获取体征数据，模拟从课题二接收
@admin_scene_realtime.post('/vital_signs')
def get_vital_signs():
    global data
    datas = request.json['datas']
    thread = threading.Thread(target=insert_signs,args=(datas,))
    thread.run()
    return jsonify({'message': 'success'})

def insert_signs(datas:list) -> None:
    for data in datas:
        user_name = data.get('police_name')
        user_id = data.get('police_code')
        heart_rate_time = data.get('heart_rate_time')
        heart_rate = data.get('heart_rate')
        temp_time = data.get('temp_time')
        temperature = data.get('temperature')
        sn = data.get('sn')
        record = SignsData2(user_id=user_id,user_name=user_name,heart_rate_time=heart_rate_time,heart_rate=heart_rate,\
                        temp_time=temp_time,temperature=temperature,sn=sn)

        db.session.add(record)
        db.session.commit()

# 图表 api
@admin_scene_realtime.get('/polling2')
def ajax_polling():

    time_now = time.strftime('%H:%M:%S ', time.localtime(time.time()))

    record = SignsData2.query.order_by(SignsData2.id.desc()).first()
    time_now = record.temp_time
    Blood_oxygen = round(random.uniform(96, 98), 2)
    blood_pressure = random.randint(110, 115)
    Respiratory_rate = random.randint(18, 26)
    heart_rate = record.heart_rate
    temperature = record.temperature
    # heart_rate = random.randint(65, 80)
    # temperature = round(random.uniform(36.2, 36.7), 2)

    return jsonify(Blood_oxygen = Blood_oxygen, blood_pressure = blood_pressure, Respiratory_rate = Respiratory_rate, \
         heart_rate = heart_rate, temperature = temperature, time_now = time_now)

# 训练结束，弹出当次训练报告
@admin_scene_realtime.get('/stop/<int:id>')
def stop(id):
    time_now=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    train2=curd.get_one_by_id(TrainData2, id)
    record = TrainData(user_id=id, type_id=train2.type_id, scene_name=train2.scene_name,train_name=train2.train_name, \
                        user_name=train2.user_name, enable=None, train_data=None, start_time=train2.start_time,\
                       end_time=time_now,train_grade=str(random.randint(70, 100)),train_recording='http://localhost:8887/video.mp4')

    db.session.add(record)

    TrainData2.query.filter_by(id=id).update({'enable': 0, 'end_time': time_now})
    db.session.commit()
    # time.sleep(2)
    end_time = datetime.datetime.now().timestamp()
    start_time = train.start_time.timestamp()
    duration = end_time - start_time
    time1 = start_time+duration/6
    time2 = time1 + duration / 6
    time3 = time2 + duration / 6
    time4 = time3 + duration / 6
    time5 = time4 + duration / 6
    time6 = time5 + duration / 6

    t_duration = datetime.datetime.now()-train.start_time


    return render_template('admin/atkdef_scene/scene_personal_report.html',
                           train=train,
                           t_min=math.floor(t_duration.seconds/60),
                           t_sec=t_duration.seconds-math.floor(t_duration.seconds/60)*60,
                           t0=datetime.datetime.fromtimestamp(start_time).strftime('%H:%M:%S'),
                           t1=datetime.datetime.fromtimestamp(time1).strftime('%H:%M:%S'),
                           t2=datetime.datetime.fromtimestamp(time2).strftime('%H:%M:%S'),
                           t3=datetime.datetime.fromtimestamp(time3).strftime('%H:%M:%S'),
                           t4=datetime.datetime.fromtimestamp(time4).strftime('%H:%M:%S'),
                           t5=datetime.datetime.fromtimestamp(time5).strftime('%H:%M:%S'),
                           t6=datetime.datetime.fromtimestamp(time6).strftime('%H:%M:%S')
                           )


# @admin_scene_realtime.get('/personal_details')
# def personal_details():
#
#     return render_template('admin/atkdef_scene/scene_personal_report.html',train = train)
#
